<template>
  <div class="container">
    <div style="width: 100%;">
      <el-image  style="width: 100%;" fit="fill" :src="require('@/assets/img/banner.png')"></el-image>

    </div>
    <div class="main">
      <el-button icon="el-icon-bicycle" circle @click="logout"></el-button>
      <!--   若今日未打卡则显示未打卡   -->
      <h4 v-if="clockFlag">你已经连续打卡{{ form.duration }}天!</h4>
      <h4 v-else>你今日尚未打卡!</h4>
      <h4 v-show="clockFlag" style="color: green;">今天已经打卡！</h4>
      <h4 v-show="!clockFlag" style="color: red;">未打卡</h4>
      <el-form ref="form" label-position="top" :model="form" :rules="rules">
        <!-- 1 师生号  **************************************** -->
        <el-form-item label="1. 师生号:" required prop="userId">
          <el-input
            v-model="form.userId"
            placeholder="请输入用户id"
            disabled
          ></el-input>
        </el-form-item>

        <!-- 2 打卡时间 ***************************  -->
        <el-form-item label="2. 打卡时间:" required>
          <el-input disabled v-model="form.clockInDate"></el-input>
        </el-form-item>

        <!-- 3 真实姓名 ***************************  -->
        <el-form-item label="3. 真实姓名:" required>
          <el-input disabled v-model="form.realname"></el-input>
        </el-form-item>

        <!-- 4 证件类型 -->
        <el-form-item label="4. 证件类型:" required prop="credentialType">
          <el-select v-model="form.credentialType" placeholder="请选择证件类型">
            <el-option label="居民身份证" value="1">居民身份证</el-option>
            <el-option label="军官证" value="2">军官证</el-option>
            <el-option label="士兵证" value="3">士兵证</el-option>
            <el-option label="文职干部证" value="4">文职干部证</el-option>
            <el-option label="部队离休证" value="5">部队离休证</el-option>
            <el-option label="香港特区护照" value="6"
              >香港特区护照/身份证</el-option
            >
            <el-option label="澳门特区护照/身份证" value="7"
              >澳门特区护照/身份证</el-option
            >
            <el-option label="台湾居民来往大陆通行证" value="8"
              >台湾居民来往大陆通行证</el-option
            >
            <el-option label="境外永久居住证" value="9"
              >境外永久居住证</el-option
            >
            <el-option label="护照" value="10">护照</el-option>
            <el-option label="户口簿" value="11">户口簿</el-option>
            <el-option label="其他" value="12">其他</el-option>
          </el-select>
        </el-form-item>

        <!-- 5 证件号码 -->
        <el-form-item label="5. 证件号码:" required prop="credentialNum">
          <el-input
            type="number"
            v-model="form.credentialNum"
            placeholder="请输入证件号码"
          ></el-input>
        </el-form-item>

        <!-- 6 身份类型 教工/学生 -->
        <el-form-item label="6. 身份类别:">
          <el-input v-model="form.userType" disabled></el-input>
        </el-form-item>

        <!-- 7 校区 -->
        <el-form-item label="7. 所在校区:" required prop="campus">
          <el-radio-group v-model="form.campus">
            <el-radio border label="1">松山湖校区</el-radio>
            <el-radio border label="2">莞城校区</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 8 地址-->
        <el-form-item label="8. 地址:" required>
          <el-cascader
            clearable
            style="width: 100%;"
            v-model="form.addressJson"
            :options="$options.options"
          ></el-cascader>
        </el-form-item>

        <!-- 9 电话 -->
        <el-form-item label="9. 手机号码:" required prop="phone">
          <el-input
            type="number"
            v-model="form.phone"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>

        <!-- 10 紧急联系人-->
        <el-form-item label="10. 紧急联系人:" required prop="urgentContact">
          <el-input
            v-model="form.urgentContact"
            placeholder="请输入紧急联系人姓名"
          ></el-input>
        </el-form-item>

        <!-- 11 紧急联系人号码-->
        <el-form-item
          label="11. 紧急联系人手机号码:"
          required
          prop="urgentPhone"
        >
          <el-input
            type="number"
            v-model="form.urgentPhone"
            placeholder="请输入紧急联系人手机号码"
          ></el-input>
        </el-form-item>

        <!-- 12 身体状况-->
        <el-form-item label="12. 身体状况:" required prop="physicalStatus">
          <el-select v-model="form.physicalStatus" placeholder="请选择身体状况">
            <el-option label="良好" value="1"></el-option>
            <el-option label="异常（体温超过37.5摄氏度）" value="2"></el-option>
            <el-option label="异常（咳嗽）" value="3"></el-option>
            <el-option label="异常（头晕）" value="4"></el-option>
            <el-option label="异常（腹泻）" value="5"></el-option>
            <el-option label="异常（乏力）" value="6"></el-option>
            <el-option
              label="异常（同时包含两种以上症状）"
              value="7"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 13 14天是否到重点地区 -->
        <el-form-item
          label="13. 最近十四天是否到达或途径疫情防控重点地区："
          required
          prop="reachDangerZone"
        >
          <el-radio-group v-model="form.reachDangerZone">
            <el-radio border label="1">是</el-radio>
            <el-radio border label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 13-1 13填是 选择去过的重点地区-->
        <el-form-item label="13-1. 重点地区" v-if="form.reachDangerZone == 1">
          <el-checkbox-group v-model="form.dangerZoneJson">
            <el-checkbox label="境外" name="form.dangerZoneJson"></el-checkbox>
            <el-checkbox label="广东省广州市荔湾区" name="form.dangerZoneJson"
              >广东省广州市荔湾区</el-checkbox
            >
            <el-checkbox
              label="广东省佛山市南海区"
              name="form.dangerZoneJson"
            ></el-checkbox>
            <el-checkbox
              label="广东省佛山市禅城区"
              name="form.dangerZoneJson"
            ></el-checkbox>
            <el-checkbox
              label="广东省广州市番禺区"
              name="form.dangerZoneJson"
            ></el-checkbox>
            <el-checkbox
              label="广东省广州市海珠区"
              name="form.dangerZoneJson"
            ></el-checkbox>
            <el-checkbox
              label="广东省广州市越秀区"
              name="form.dangerZoneJson"
            ></el-checkbox>
            <el-checkbox
              label="广东省广州市南沙区"
              name="form.dangerZoneJson"
            ></el-checkbox>
            <el-checkbox
              label="广东省湛江市昊川市"
              name="form.dangerZoneJson"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 13-2 13填是 离开重点地区的时间-->
        <el-form-item
          label="13-2. 最后离开途径疫区的时间:"
          v-if="form.reachDangerZone == '1'"
        >
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="form.leaveDangerTime"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>

        <!-- 14 是否接触重点区的人 -->
        <el-form-item
          required
          prop="touchDangerPeople"
          label="14. 最近十四天是否接触过“近14天出入过疫情重点防控地区”的人员："
        >
          <el-radio-group v-model="form.touchDangerPeople">
            <el-radio border label="1">是</el-radio>
            <el-radio border label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 14-1 14填是 最后接触重点区人的时间-->
        <el-form-item
          label="14-1. 接触“近14天出入过疫情重点防控地区人员”的最后时间："
          v-if="form.touchDangerPeople == 1"
        >
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="form.lastTouchPeopleTime"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>

        <!-- 15 是否接触疑似病例-->
        <el-form-item
          required
          label="15. 最近十四天是否接触过疑似病例/确诊病例: "
          prop="touchCase"
        >
          <el-radio-group v-model="form.touchCase">
            <el-radio border label="1">是</el-radio>
            <el-radio border label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 15-1 15填是 最后接触疑似病例的时间-->
        <el-form-item
          label="15-1. 接触过疑似病例/确诊病例的最后时间"
          v-if="form.touchCase == 1"
        >
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="form.lastTouchCaseTime"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>

        <!-- 16 是否隔离医学观察 -->
        <el-form-item
          label="16. 是否在莞隔离医学观察 "
          required
          prop="isolation"
        >
          <el-radio-group v-model="form.isolation">
            <el-radio border label="0">否，没有隔离</el-radio>
            <el-radio border label="1">是，正在隔离</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 16-1 终止隔离的时间 -->
        <el-form-item label="16-1. 终止隔离的时间" v-if="form.isolation == 1">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="form.endTime"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>

        <!-- 17 今日体温 -->
        <el-form-item label="17. 今日体温:" required>
          <el-input
            type="number"
            v-model="form.temp"
            placeholder="请输入体温"
            prop="temp"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            v-show="!clockFlag"
            class="btn"
            type="primary"
            :disabled="btnDisabled"
            @click="submitForm('form')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import {logout, quest,  questPostInMq} from "../network/index.js";
import { regionData } from "element-china-area-data";
import {getPollingRes} from "network/index";

export default {
  name: "Layout",
  methods: {
    open() {
      this.$message({
        message: "打卡成功",
        type: "success",
      });
    },
    postTimeOut(){
      this.$message({
        message: "打卡超时，请重试",
        type: "success",
      });
    },
    postSuccess(){
      this.open();
      this.clockFlag = true;
      this.form.duration += 1;  /*成功后打卡天数加1*/
      window.scrollTo(0,0); /*并且页面滚动至顶部*/
    },
    submitForm(form) {
      this.btnDisabled=true; /*提交表单后让按钮失效3s，防止重复提交*/
      setTimeout(()=>this.btnDisabled=false,3000);
      //提交打卡后开启Loading
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$refs[form].validate((vaild) => {
        if (vaild) {
          //日期格式数据转换
          this.form.endTime = new Date(this.form.endTime).format("yyyy-MM-dd");
          this.form.lastTouchCaseTime = new Date( this.form.lastTouchCaseTime).format("yyyy-MM-dd");
          this.form.lastTouchPeopleTime = new Date(this.form.lastTouchPeopleTime).format("yyyy-MM-dd");
          this.form.leaveDangerTime = new Date(this.form.leaveDangerTime).format("yyyy-MM-dd");

          //数据整理
          let postData = {
            credentialType: parseInt(this.form.credentialType),
            credentialNum: this.form.credentialNum,
            campus: parseInt(this.form.campus),
            addressJson: this.form.addressJson,
            phone: this.form.phone,
            urgentContact: this.form.urgentContact,
            urgentPhone: this.form.urgentPhone,
            physicalStatus: parseInt(this.form.physicalStatus),
            reachDangerZone: parseInt(this.form.reachDangerZone),

            touchDangerPeople: parseInt(this.form.touchDangerPeople),

            touchCase: parseInt(this.form.touchCase),

            isolation: parseInt(this.form.isolation),

            temp: this.form.temp,
          };
          //可选项要是选择否 子选项的值就会为undefined
          if (this.form.reachDangerZone == "1") {
            postData.dangerZoneJson = this.form.dangerZoneJson;
            postData.leaveDangerTime = this.form.leaveDangerTime;
          }
          if (this.form.touchDangerPeople == "1") {
            postData.lastTouchPeopleTime = this.form.lastTouchPeopleTime;
          }

          if (this.form.touchCase == "1") {
            postData.lastTouchCaseTime = this.form.lastTouchCaseTime;
          }

          if (this.form.isolation == "1") {
            postData.endTime = this.form.endTime;
          }
          let token = this.$store.getters.getToken;

          /*正常提交版本的接口*/
          // questPost(token, postData)
          //   .then((res) => {
          //     console.log(res);
          //     //成功隐藏提交按钮
          //     if (res.data.code == 201) {
          //       this.open();
          //       this.clockFlag = true;
          //       this.form.duration += 1;  /*成功后打卡天数加1*/
          //       window.scrollTo(0,0); /*并且页面滚动至顶部*/
          //     } else throw new Error(res);
          //   })
          //   .catch((error) => {
          //     console.log(error);
          //   });

          /*利用MQ提交解决高并发问题的接口*/
          questPostInMq(token, postData)
              .then((res) => {
                console.log(res);
                //成功提交，轮询查看结果
                let cnt = 0;  //轮询次数
                let pollingFunc =  ()=>{
                  getPollingRes(token).then(res=> {
                    if (res.data.code == 200 || cnt>5) {
                      if(cnt>5){ //打卡失败
                        this.postTimeOut()
                      }
                      else{ //打卡成功
                        this.postSuccess()
                      }
                      loading.close();  //关闭loading
                      clearInterval(timeId) //清除定时器
                    }
                    cnt++;
                  })
                }
                const timeId = setInterval(pollingFunc,2000)  //定义并开启定时器
              })
              .catch(console.log)

      }});
    },
    logout() {
      let token = Cookies.get("token");
      Cookies.remove("token");
      logout(token).then((res) => {
        console.log(res);
      });
      //请求发出登出
      location.reload();
      this.$router.push("/");
    },
  },
  data() {
    return {
      btnDisabled: false,  /*提交按钮是否有效,初始化false表示有效*/
      //打卡表单的数据
      form: {
        //1 用户id
        userId: "",

        //2 打卡时间
        clockInDate: new Date().toString(),

        //3 连续打卡时间
        duration: 0,

        //4 证件类型
        credentialType: "",

        //5 证件号码
        credentialNum: "",

        //6 教工 / 学生
        userType: "",

        //7 校区
        campus: "1",

        //8 地址
        addressJson: [],

        //9 电话
        phone: "",

        //10 紧急联系人
        urgentContact: "",

        //11 紧急联系人号码
        urgentPhone: "",

        //12 身体状况
        physicalStatus: "",

        //13 14天是否到重点地区
        reachDangerZone: "",

        //13-1 13填是 选择去过的重点地区
        dangerZoneJson: [],

        //13-2 13填是 离开重点地区的时间
        leaveDangerTime: "",

        //14 是否接触重点区的人
        touchDangerPeople: "",

        //14-1 14填是 最后接触重点区人的时间
        lastTouchPeopleTime: "",

        //15 是否接触疑似病例
        touchCase: "",

        //15-1 15填是 最后接触疑似病例的时间
        lastTouchCaseTime: "",

        //16 是否隔离医学观察
        isolation: "",

        //16-1 终止隔离的时间
        endTime: "",

        //17 今日体温
        temp: "",

        realname: "",
      },
      dangeDistrict: false,
      rules: {
        userId: [
          { required: true, message: "请输入你的职工号/学号", trigger: "blur" },
        ],
        credentialType: [
          { required: true, message: "请选择证件类型", trigger: "blur" },
        ],
        credentialNum: [
          { required: true, message: "请填写证件号码", trigger: "blur" },
        ],
        campus: [
          { required: true, message: "请选择所在校区", trigger: "blur" },
        ],
        addressJson: [
          {
            type: "array",
            required: true,
            message: "请填写地址",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入你的手机号", trigger: "blur" },
        ],
        urgentContact: [
          { required: true, message: "请输入紧急联系人", trigger: "blur" },
        ],
        urgentPhone: [
          {
            required: true,
            message: "请输入紧急联系人手机号码",
            trigger: "blur",
          },
        ],
        physicalStatus: [
          { required: true, message: "请选择身体状况", trigger: "blur" },
        ],
        reachDangerZone: [
          { required: true, message: "请选择是否", trigger: "blur" },
        ],
        touchDangerPeople: [
          { required: true, message: "请选择是否", trigger: "blur" },
        ],
        touchCase: [{ required: true, message: "请选择是否", trigger: "blur" }],
        isolation: [{ required: true, message: "请选择是否", trigger: "blur" }],
        temp: [{ required: true, message: "请输入体温", trigger: "blur" }],
      },
      //今日打卡成功的标志
      clockFlag: false,
    };
  },
  options: regionData, //自定义options
  created() {
    //1、查询上一次的数据
    {
      let token = Cookies.get("token");
      let user = this.$store.getters.getLoginUserData;

      //从token获取数据直接显示
      this.form.clockInDate = new Date().format("yyyy-MM-dd");
      this.form.userId = user.username;
      this.form.realname = user.realName;
      this.form.userType = user.userType == 1 ? "学生" : "教师";

      quest(token)
        .then((res) => {
          //成功获取上一次的信息
          if (res.data.code === 200) {
            let reqData = res.data.data;

            //对比现在时间和上一次的时间，避免重复提交
            let lastDay = new Date(reqData.clockInDate.substring(0, 10));
            let nowDay = new Date();

            if (
              lastDay.getFullYear() === nowDay.getFullYear() &&
              lastDay.getMonth() === nowDay.getMonth() &&
              lastDay.getDate() === nowDay.getDate()
            ) {
              this.clockFlag = true;
            } else this.clockFlag = false;
            //获取昨天的时间，用于判断连续打卡时间
            let yesterday = new Date(new Date()-24*60*60*1000);
            if (  //上一次打卡的是昨天或者是今天才显示duration,否则连续打卡天数是0
                lastDay.getFullYear() === yesterday.getFullYear() &&
                lastDay.getMonth() === yesterday.getMonth() &&
                lastDay.getDate() === yesterday.getDate() ||
                this.clockFlag
            )this.form.duration = reqData.duration;
            else this.form.duration = 0;
                //保存数据
            //(this.form.duration = reqData.duration),
              (this.form.credentialType = String(reqData.credentialType)),
              (this.form.credentialNum = reqData.credentialNum),
              (this.form.campus = String(reqData.campus)),
              (this.form.addressJson = reqData.addressJson),
              (this.form.phone = reqData.phone),
              (this.form.urgentContact = reqData.urgentContact),
              (this.form.urgentPhone = reqData.urgentPhone),
              (this.form.physicalStatus = String(reqData.physicalStatus)),
              (this.form.reachDangerZone = String(reqData.reachDangerZone)),
              (this.form.dangerZoneJson = reqData.dangerZoneJson),
              (this.form.leaveDangerTime = reqData.leaveDangerTime),
              (this.form.touchDangerPeople = String(reqData.touchDangerPeople)),
              (this.form.lastTouchPeopleTime = reqData.lastTouchPeopleTime),
              (this.form.touchCase = String(reqData.touchCase)),
              (this.form.lastTouchCaseTime = reqData.lastTouchCaseTime),
              (this.form.isolation = String(reqData.isolation)),
              (this.form.endTime = reqData.endTime),
              (this.form.temp = Number(reqData.temp));
          } else throw new Error("该用户没有上一条记录");
        })
        .catch((error) => {
          console.log(error);
        });
    }
  },
};
</script>

<style scoped>
.btn {
  display: block;
  margin: 5px auto;
}
h4 {
  text-align: center;
}
.container {
  /* border: 1px solid black; */
  margin: 0px auto;
  /* width: 95%; */
}
.main {
  width: 90%;
  margin: 0 auto;
}
</style>
